home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / static.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-03-23  |  17KB  |  382 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''I deal with static resources.
  5. '''
  6. import os
  7. import string
  8. import time
  9. import cStringIO
  10. import traceback
  11. import warnings
  12. StringIO = cStringIO
  13. del cStringIO
  14. from zope.interface import implements
  15. from twisted.web import error
  16. from twisted.web.util import redirectTo
  17.  
  18. try:
  19.     from twisted.web import http
  20. except ImportError:
  21.     from twisted.protocols import http
  22.  
  23. from twisted.python import threadable, log, components, filepath
  24. from twisted.internet import abstract
  25. from twisted.spread import pb
  26. from twisted.python.util import InsensitiveDict
  27. from twisted.python.runtime import platformType
  28. from nevow import appserver, dirlist, inevow, rend
  29. dangerousPathError = error.NoResource('Invalid request URL.')
  30.  
  31. def isDangerous(path):
  32.     if not path == '..' and '/' in path:
  33.         pass
  34.     return os.sep in path
  35.  
  36.  
  37. class Data:
  38.     '''
  39.     This is a static, in-memory resource.
  40.     '''
  41.     implements(inevow.IResource)
  42.     
  43.     def __init__(self, data, type, expires = None):
  44.         self.data = data
  45.         self.type = type
  46.         self.expires = expires
  47.  
  48.     
  49.     def time(self):
  50.         '''
  51.         Return the current time as a float.
  52.  
  53.         The default implementation simply uses L{time.time}.  This is mainly
  54.         provided as a hook for tests to override.
  55.         '''
  56.         return time.time()
  57.  
  58.     
  59.     def locateChild(self, ctx, segments):
  60.         return appserver.NotFound
  61.  
  62.     
  63.     def renderHTTP(self, ctx):
  64.         request = inevow.IRequest(ctx)
  65.         request.setHeader('content-type', self.type)
  66.         request.setHeader('content-length', str(len(self.data)))
  67.         if self.expires is not None:
  68.             request.setHeader('expires', http.datetimeToString(self.time() + self.expires))
  69.         
  70.         if request.method == 'HEAD':
  71.             return ''
  72.         return self.data
  73.  
  74.  
  75.  
  76. def staticHTML(someString):
  77.     return Data(someString, 'text/html')
  78.  
  79.  
  80. def addSlash(request):
  81.     if not request.isSecure() or 's':
  82.         pass
  83.     return 'http%s://%s%s/' % ('', request.getHeader('host'), string.split(request.uri, '?')[0])
  84.  
  85.  
  86. class Registry(components.Componentized):
  87.     '''
  88.     I am a Componentized object that will be made available to internal Twisted
  89.     file-based dynamic web content such as .rpy and .epy scripts.
  90.     '''
  91.     
  92.     def __init__(self):
  93.         components.Componentized.__init__(self)
  94.         self._pathCache = { }
  95.  
  96.     
  97.     def cachePath(self, path, rsrc):
  98.         self._pathCache[path] = rsrc
  99.  
  100.     
  101.     def getCachedPath(self, path):
  102.         return self._pathCache.get(path)
  103.  
  104.  
  105.  
  106. def loadMimeTypes(mimetype_locations = [
  107.     '/etc/mime.types']):
  108.     '''
  109.     Multiple file locations containing mime-types can be passed as a list.
  110.     The files will be sourced in that order, overriding mime-types from the
  111.     files sourced beforehand, but only if a new entry explicitly overrides
  112.     the current entry.
  113.     '''
  114.     import mimetypes as mimetypes
  115.     contentTypes = mimetypes.types_map
  116.     contentTypes.update({
  117.         '.conf': 'text/plain',
  118.         '.diff': 'text/plain',
  119.         '.exe': 'application/x-executable',
  120.         '.flac': 'audio/x-flac',
  121.         '.java': 'text/plain',
  122.         '.ogg': 'application/ogg',
  123.         '.oz': 'text/x-oz',
  124.         '.swf': 'application/x-shockwave-flash',
  125.         '.tgz': 'application/x-gtar',
  126.         '.wml': 'text/vnd.wap.wml',
  127.         '.xul': 'application/vnd.mozilla.xul+xml',
  128.         '.py': 'text/plain',
  129.         '.patch': 'text/plain',
  130.         '.pjpeg': 'image/pjpeg',
  131.         '.tac': 'text/x-python' })
  132.     for location in mimetype_locations:
  133.         if os.path.exists(location):
  134.             contentTypes.update(mimetypes.read_mime_types(location))
  135.             continue
  136.     
  137.     return contentTypes
  138.  
  139.  
  140. def getTypeAndEncoding(filename, types, encodings, defaultType):
  141.     (p, ext) = os.path.splitext(filename)
  142.     ext = ext.lower()
  143.     if encodings.has_key(ext):
  144.         enc = encodings[ext]
  145.         ext = os.path.splitext(p)[1].lower()
  146.     else:
  147.         enc = None
  148.     type = types.get(ext, defaultType)
  149.     return (type, enc)
  150.  
  151.  
  152. class File:
  153.     """
  154.     File is a resource that represents a plain non-interpreted file
  155.     (although it can look for an extension like .rpy or .cgi and hand the
  156.     file to a processor for interpretation if you wish). Its constructor
  157.     takes a file path.
  158.  
  159.     Alternatively, you can give a directory path to the constructor. In this
  160.     case the resource will represent that directory, and its children will
  161.     be files underneath that directory. This provides access to an entire
  162.     filesystem tree with a single Resource.
  163.  
  164.     If you map the URL 'http://server/FILE' to a resource created as
  165.     File('/tmp'), then http://server/FILE/ will return an HTML-formatted
  166.     listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will
  167.     return the contents of /tmp/foo/bar.html .
  168.     """
  169.     implements(inevow.IResource)
  170.     contentTypes = loadMimeTypes()
  171.     contentEncodings = {
  172.         '.gz': 'application/x-gzip',
  173.         '.bz2': 'application/x-bzip2' }
  174.     processors = { }
  175.     indexNames = [
  176.         'index',
  177.         'index.html',
  178.         'index.htm',
  179.         'index.trp',
  180.         'index.rpy']
  181.     type = None
  182.     
  183.     def __init__(self, path, defaultType = 'text/html', ignoredExts = (), registry = None, allowExt = 0):
  184.         '''Create a file with the given path.
  185.         '''
  186.         self.fp = filepath.FilePath(path)
  187.         self.defaultType = defaultType
  188.         if ignoredExts in (0, 1) or allowExt:
  189.             warnings.warn('ignoredExts should receive a list, not a boolean')
  190.             if ignoredExts or allowExt:
  191.                 self.ignoredExts = [
  192.                     '*']
  193.             else:
  194.                 self.ignoredExts = []
  195.         else:
  196.             self.ignoredExts = list(ignoredExts)
  197.         if not registry:
  198.             pass
  199.         self.registry = Registry()
  200.         self.children = { }
  201.  
  202.     
  203.     def ignoreExt(self, ext):
  204.         '''Ignore the given extension.
  205.  
  206.         Serve file.ext if file is requested
  207.         '''
  208.         self.ignoredExts.append(ext)
  209.  
  210.     
  211.     def directoryListing(self):
  212.         return dirlist.DirectoryLister(self.fp.path, self.listNames(), self.contentTypes, self.contentEncodings, self.defaultType)
  213.  
  214.     
  215.     def putChild(self, name, child):
  216.         self.children[name] = child
  217.  
  218.     
  219.     def locateChild(self, ctx, segments):
  220.         r = self.children.get(segments[0], None)
  221.         if r:
  222.             return (r, segments[1:])
  223.         path = segments[0]
  224.         self.fp.restat()
  225.         if not self.fp.isdir():
  226.             return rend.NotFound
  227.         if fpath.isfile():
  228.             if platformType == 'win32':
  229.                 processor = InsensitiveDict(self.processors).get(fpath.splitext()[1])
  230.             else:
  231.                 processor = self.processors.get(fpath.splitext()[1])
  232.             if processor:
  233.                 return (inevow.IResource(processor(fpath.path, self.registry)), segments[1:])
  234.         
  235.         return (self.createSimilarFile(fpath.path), segments[1:])
  236.  
  237.     
  238.     def openForReading(self):
  239.         '''Open a file and return it.'''
  240.         return self.fp.open()
  241.  
  242.     
  243.     def getFileSize(self):
  244.         '''Return file size.'''
  245.         return self.fp.getsize()
  246.  
  247.     
  248.     def renderHTTP(self, ctx):
  249.         '''You know what you doing.'''
  250.         self.fp.restat()
  251.         if self.type is None:
  252.             (self.type, self.encoding) = getTypeAndEncoding(self.fp.basename(), self.contentTypes, self.contentEncodings, self.defaultType)
  253.         
  254.         if not self.fp.exists():
  255.             return rend.FourOhFour()
  256.         request = inevow.IRequest(ctx)
  257.         if self.fp.isdir():
  258.             return self.redirect(request)
  259.         request.setHeader('accept-ranges', 'bytes')
  260.         if self.encoding:
  261.             request.setHeader('content-encoding', self.encoding)
  262.         
  263.         
  264.         try:
  265.             f = self.openForReading()
  266.         except IOError:
  267.             e = None
  268.             import errno as errno
  269.             if e[0] == errno.EACCES:
  270.                 return error.ForbiddenResource().render(request)
  271.             raise 
  272.         except:
  273.             e[0] == errno.EACCES
  274.  
  275.         if request.setLastModified(self.fp.getmtime()) is http.CACHED:
  276.             return ''
  277.         
  278.         try:
  279.             range = request.getHeader('range')
  280.             request.setHeader('content-length', str(size))
  281.         except:
  282.             request.setLastModified(self.fp.getmtime()) is http.CACHED
  283.             e[0] == errno.EACCES
  284.             traceback.print_exc(file = log.logfile)
  285.  
  286.         if request.method == 'HEAD':
  287.             return ''
  288.         FileTransfer(f, size, request)
  289.         return request.deferred
  290.  
  291.     
  292.     def redirect(self, request):
  293.         return redirectTo(addSlash(request), request)
  294.  
  295.     
  296.     def listNames(self):
  297.         if not self.fp.isdir():
  298.             return []
  299.         directory = self.fp.listdir()
  300.         directory.sort()
  301.         return directory
  302.  
  303.     
  304.     def createSimilarFile(self, path):
  305.         f = self.__class__(path, self.defaultType, self.ignoredExts, self.registry)
  306.         f.processors = self.processors
  307.         f.indexNames = self.indexNames[:]
  308.         return f
  309.  
  310.  
  311.  
  312. class FileTransfer(pb.Viewable):
  313.     '''
  314.     A class to represent the transfer of a file over the network.
  315.     '''
  316.     request = None
  317.     
  318.     def __init__(self, file, size, request):
  319.         self.file = file
  320.         self.size = size
  321.         self.request = request
  322.         request.registerProducer(self, 0)
  323.  
  324.     
  325.     def resumeProducing(self):
  326.         if not self.request:
  327.             return None
  328.         data = self.file.read(min(abstract.FileDescriptor.bufferSize, self.size))
  329.         if self.size <= 0:
  330.             self.request.unregisterProducer()
  331.             self.request.finish()
  332.             self.request = None
  333.         
  334.  
  335.     
  336.     def pauseProducing(self):
  337.         pass
  338.  
  339.     
  340.     def stopProducing(self):
  341.         self.file.close()
  342.         self.request = None
  343.  
  344.     
  345.     def view_resumeProducing(self, issuer):
  346.         self.resumeProducing()
  347.  
  348.     
  349.     def view_pauseProducing(self, issuer):
  350.         self.pauseProducing()
  351.  
  352.     
  353.     def view_stopProducing(self, issuer):
  354.         self.stopProducing()
  355.  
  356.     synchronized = [
  357.         'resumeProducing',
  358.         'stopProducing']
  359.  
  360. threadable.synchronize(FileTransfer)
  361.  
  362. class ASISProcessor:
  363.     implements(inevow.IResource)
  364.     
  365.     def __init__(self, path, registry = None):
  366.         self.path = path
  367.         if not registry:
  368.             pass
  369.         self.registry = Registry()
  370.  
  371.     
  372.     def renderHTTP(self, ctx):
  373.         request = inevow.IRequest(ctx)
  374.         request.startedWriting = 1
  375.         return File(self.path, registry = self.registry)
  376.  
  377.     
  378.     def locateChild(self, ctx, segments):
  379.         return appserver.NotFound
  380.  
  381.  
  382.